package com.leyou.auth.interceptor;

import com.leyou.auth.utils.UserHolder;
import com.leyou.common.constants.JwtConstants;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.pojo.dto.Payload;
import com.leyou.pojo.util.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 配置拦截器，拦截请求，检查用户是否登录
 */
public class LoginInterceptor implements HandlerInterceptor {
    //因为拦截器没有必要注入到spring中，所有变量只能通过构造方法复制
    private JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils){
        this.jwtUtils=jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie中的jwt
        String cookieValue = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        //判断是否存在，
        if (cookieValue == null) {
            throw new LyException("用户未登录",401);
        }
        //解析jwt
        //在工具类中对结果已经进行你了判断，所以外面不用在进行判断
        Payload payload = jwtUtils.parseJwtAndRedis(cookieValue);
        //在解析jwt的时候，同时也要对比jti，如果不同，则用户未登录，这个可以写在解析jwt中
        //存储用户信息
        UserHolder.set(payload.getUserDetail());
        //正确，放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
